
/*    This file is part of the Managarm operating system.
 *   Copyright (C) 2007, 2008, 2009  Alexander van der Grinten
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

import java.net.Socket;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
	public static void main(String[] arguments) {
		if(arguments.length < 3) {
			System.err.println("Usage: java JScriptClient HOST PORT [ARGS..]");
			System.exit(1);
		}
		

		final StringBuffer cmdline = new StringBuffer();
		for(int i = 2; i < arguments.length; i++) {
			cmdline.append(arguments[i]);
			cmdline.append(" ");
		}
		cmdline.append("\n");
		
		final String hostname = arguments[0];
		final int portnumber = Integer.parseInt(arguments[1]);
		try {
			final Socket socket = new Socket(hostname, portnumber);
			final InputStreamReader instream =
					new InputStreamReader(socket.getInputStream());
			final OutputStreamWriter outstream =
					new OutputStreamWriter(socket.getOutputStream());
			
			outstream.write(cmdline.toString());
			outstream.flush();
			
			// read the input characters
			final StringBuffer buffer = new StringBuffer();
			while(true) {
				final int c = instream.read();
				if(c == 0)
					break;
				buffer.append((char)c);
			}
			final String string = buffer.toString();
			
			if(string.equals("okay"))
				return;
			System.err.println("Error while executing script. Reason:");
			System.err.println(string);
			System.exit(1);
		} catch (IOException e) {
			System.err.println("Communication error: " + e.getMessage());
			System.exit(1);
		}
	}

}
